package com.wcfsy.wechat.wx.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.Map;

import javax.annotation.Resource;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.ParseException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.wcfsy.wechat.wx.entity.TemplateData;
import com.wcfsy.wechat.wx.entity.WxTemplate;

@Component("pushMessage")
public class PushMessage {
	
	@Resource
	private WechatUtil wechatUtil;

	 
	Logger logger = LoggerFactory.getLogger(this.getClass());
	
	private void callBack(HttpServletRequest request,HttpServletResponse response,JSONObject json){
		//可以先在这里验证签名
		StringBuilder sb = new StringBuilder();
		BufferedReader in = null;
		try {
			in = request.getReader();
			String line;
			while ((line = in.readLine()) != null) {
				sb.append(line);
			}
			in.close();
			String xml = sb.toString();
			logger.info("----环信回调的客服消息内容 = " + xml);//这个xml就是环信回调回来的消息
			if(StringUtils.isEmpty(xml)){
			}
			JSONObject message = JSONObject.parseObject(xml);
			String url = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=" + wechatUtil.getToken().getString("access_token");//getAccessToken();
			logger.info("给微信发消息地址:" + url);
			DefaultHttpClient client = new DefaultHttpClient();
			enableSSLDefaultHttpClient(client);
			HttpPost httpPost = new HttpPost(url);
			JSONObject messages = new JSONObject();
			String type = ((JSONObject)(message.getJSONObject("payload").getJSONArray("bodies").get(0))).getString("type");
			switch (type) {
			case "txt":
				String content = ((JSONObject)(message.getJSONObject("payload").getJSONArray("bodies").get(0))).getString("msg");
				String toUser = message.getJSONObject("payload").getJSONObject("ext").getJSONObject("weichat").getJSONObject("visitor").getString("openid");
				JSONObject msg = new JSONObject();
				msg.put("msg", content);
				messages = processWechatTextMessage(client, httpPost, toUser, msg);
				break;
			default:
				logger.warn("unknown channelType = " + type);
				break;
			}
			logger.info("messages = " + messages);
		} catch (Exception e) {
			logger.info("发送消息失败 : " ,e);
		}
	}
	
	
	public JSONObject processWechatTextMessage(DefaultHttpClient client, HttpPost httpPost, String toUser, JSONObject msg) throws UnsupportedEncodingException {
		JSONObject json = new JSONObject();
		json.put("touser", toUser);
		json.put("msgtype", "text");
		JSONObject jsonContent = new JSONObject();
		jsonContent.put("content", (String) msg.get("msg"));
		json.put("text", jsonContent);
		StringEntity params = new StringEntity(json.toString(), "UTF-8");
		httpPost.setEntity(params);

		HttpResponse httpResponse = null;
		String jsonString = "";
		try {
			httpResponse = client.execute(httpPost);
			HttpEntity entity = httpResponse.getEntity();
			jsonString = EntityUtils.toString(entity);
		} catch (ParseException | IOException e) {
			logger.warn("send text message to wechat vistor {"+toUser+"} occurs warn，accept jsonString = {"+jsonString+"},and warn message = {}",  e);
			throw new RuntimeException("warn" + e.getMessage());
		}
		JSONObject messages = JSONObject.parseObject(jsonString);
		int errcode = messages.getInteger("errcode");
		if(errcode != 0 ){
			logger.warn("send text message to wechat vistor {} occurs warn，accept jsonString = {}",toUser,jsonString);
			throw new RuntimeException("failed to send message");
		}
		return messages;
	}
	public DefaultHttpClient enableSSLDefaultHttpClient(DefaultHttpClient client) {
		X509TrustManager xtm = new X509TrustManager() {
			public void checkClientTrusted(X509Certificate[] chain,
					String authType) throws CertificateException {
			}

			public void checkServerTrusted(X509Certificate[] chain,
					String authType) throws CertificateException {
			}

			public X509Certificate[] getAcceptedIssuers() {
				return null;
			}
		};
		try {
			SSLContext ctx = SSLContext.getInstance("TLS");
			ctx.init(null, new TrustManager[] { xtm }, null);
			SSLSocketFactory socketFactory = new SSLSocketFactory(ctx);
			client.getConnectionManager().getSchemeRegistry()
					.register(new Scheme("https", 443, socketFactory));
		} catch (Exception e) {
			throw new RuntimeException();
		}
		return client;
	}
	
	
	/**
	 * @param url 模板链接地址
	 * @param openId 发送客户的ID
	 * @param templateId 模板ID
	 * @param title 标题
	 * @param name 名字
	 * @param remark 描述
	 * @return
	 */
	public JSONObject createTemplateMessage(String url,String openId,String templateId,Map<String,TemplateData> map){
		WxTemplate t = new WxTemplate();  
        t.setUrl(url);  
        t.setTouser(openId);  
        t.setTopcolor("#000000");  
        t.setTemplate_id(templateId);  
        t.setData(map); 
       return (JSONObject) JSON.toJSON(t);
	}
	
	public static void addTemplateData(String name,String value,Map<String,TemplateData> map){
		TemplateData templateData = new TemplateData();  
        templateData.setColor("#173177");  
        templateData.setValue(value);  
        map.put(name, templateData);
	}
	
	/**
	 *  获取模板ID
	 * @param token
	 * @param templateIdShort
	 * @return
	 */
	public String getTemplateId(String token,String templateIdShort){
		String url = Constant.GET_TEMPLATE_ID + token;
		JSONObject json = new JSONObject();
		json.put("template_id_short", templateIdShort);
		logger.info("获取模板IDjson =  " + json);
		try {
			String result = HttpUtil.getInstance().phpPost(url,json);
			logger.info("微信获取模板返回的数据 result = " + result);
			JSONObject jsonResult = JSONObject.parseObject(result);
			int code = jsonResult.getInteger("errcode");
			if(code != 0){
				return WechatUtil.resultMessage(-1,"获取模板ID 失败" + result);
			}
			return jsonResult.getString("template_id");
		} catch (Exception e) {
			logger.warn("获取模板ID 失败 " , e);
		}
		return null;
	}
	
	public String sendTemplateMessage(String openId,String templateId,Map<String,TemplateData> map,String url){
		String result = "";
		try {
			if(StringUtils.isEmpty(openId)){
				logger.warn("openId is null ");
				return WechatUtil.resultMessage(-1,"openId is null");
			}else if(StringUtils.isEmpty(templateId)){
				logger.warn("templateId is null ");
				return WechatUtil.resultMessage(-1,"templateId is null");
			}
			JSONObject token = null;
			try {
				//token = JSONObject.parseObject(HttpClientUtil.get(Constant.SING_NAME_URL+"?appId="+Constant.APP_ID+"&secret="+Constant.APP_SECRET+"&grant_type="+Constant.CLIENT_CREDENTIAL));
				token =wechatUtil.getToken();
				logger.info("token ========= " + token);
			} catch (Exception e) {
				logger.warn("get token error ！" , e);
				return WechatUtil.resultMessage(-1,"token is null");
			}
//			Map<String,TemplateData> map = new HashMap<String,TemplateData>();
//			addTemplateData("first","您购买的天添牛回款通知",map);
//			addTemplateData("keyword1","尾号3456",map);
//			addTemplateData("keyword2","88000.00",map);
//			addTemplateData("keyword3","2015年11月05日",map);
//			addTemplateData("remark","224小时内到账，请注意查收，个别银行到账时间会晚1~2天。 如有疑问，请拨打咨询热线 4008-888-888",map);
			//创建模板消息
			JSONObject jsonObject = createTemplateMessage(url,openId,templateId,map);
			logger.info("Template 数据:  " + jsonObject.toJSONString());
			if(token != null && StringUtils.isNotEmpty(token.getString("access_token"))){
				result = HttpUtil.getInstance().phpPost(Constant.SEND_TEMPLATE_URL + token.getString("access_token"),jsonObject);
				logger.info("推送微信返回结果数据: =====================" + result);
				JSONObject  jsonResult = JSONObject.parseObject(result);
				logger.info("推送微信返回结果数据: " + result);
				int code = jsonResult.getInteger("errcode");
				if(code != 0 ){
					return WechatUtil.resultMessage(-1,"推送失败");
				}
				return WechatUtil.resultMessage(0,"推送成功");
			}else{
				return WechatUtil.resultMessage(-1,"推送失败 token is null");
			}
		} catch (Exception e) {
			logger.warn("get token error ！" , e);
			return WechatUtil.resultMessage(-1,"获取token 异常");
		}
	}
	
}
